#include "../include/userMananger.hpp"
#include "../include/user.hpp"
#include "../include/TcpConnection.h"
#include "../include/MyLogger.hpp"

#include <iostream>
using std::cout;
using std::endl;

namespace rocket 
{

rocket::userMananger *rocket::userMananger::_p_mananger=nullptr;
pthread_once_t rocket::userMananger::_once=PTHREAD_ONCE_INIT;
rocket::userMananger::autoRelease rocket::userMananger::_auto;

userMananger *userMananger::get_instance()
{
    pthread_once(&_once,init);
    return _p_mananger;
}

void userMananger::add_user(int fd,user client)
{
    if(_users.count(fd)==0)
    {
        _users.insert(std::pair<int,user>(fd,client));
        LOG_INFO("添加用户成功");    
    }
    else
    {
        LOG_INFO("添加用户失败");   
        _users.at(fd)._status=client._status;
    }
}

void userMananger::delete_user(int fd)
{
    std::map<int,rocket::user>::iterator it=_users.find(fd);
    if(it!=_users.end())
    {
        _users.erase(it);
        LOG_INFO("删除用户成功");    

    }
    else
    {
        LOG_INFO("删除用户失败");    
    }
}

void userMananger::modify_user(int fd,userStatus status)
{
    std::map<int,rocket::user>::iterator it=_users.find(fd);
    if(it!=_users.end())
    {
        it->second._status=status;
        LOG_INFO("修改用户状态成功");    

    }  
    else
    {
        LOG_INFO("修改用户状态失败");    
    }  
}

user *userMananger::get_user(int fd)
{
    return &(_users.at(fd));
}

void userMananger::init()
{
    _p_mananger=new userMananger();
}

userMananger::autoRelease::~autoRelease()
{
    if(_p_mananger!=nullptr)
    {
        delete _p_mananger;
        _p_mananger=nullptr;
    }
}

}//end of namespace rocket
